package com.zane.common.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zane.entity.User;
import com.zane.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MyUserDetailsService extends ServiceImpl<UserMapper, User> implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库获取用户信息
        log.info("根据用户名：{}，从数据库获取用户信息", username);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username);
        User one = getOne(wrapper);
        if(one == null){
            log.warn("用户不存在：{}", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        // 硬编码设置用户的权限列表
       /* List<GrantedAuthority> perms = List.of("sys:view", "sys:list").stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());*/
        List<GrantedAuthority> perms = Collections.emptyList();
        // 创建MyUserDetails对象
        MyUserDetails userDetails =  MyUserDetails.builder()
                .userId(one.getUserId())
                .username(one.getUsername())
                .password(one.getPassword())
                .roleName("ROLE_" + one.getRole())
                .perms(perms).build();
        log.info("创建MyUserDetails对象：{}", userDetails);
        return userDetails;
    }
}
